package com.zbkj.admin.controller.publicly;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.lmax.disruptor.RingBuffer;
import com.zbkj.admin.boot.redisson.queue.RDQEventPublisher;
import com.zbkj.admin.disruptor.DisruptorConfig;
import com.zbkj.admin.disruptor.OrderEvent;
import com.zbkj.admin.disruptor.OrderEventProducer;
import com.zbkj.admin.model.order.Order;
import com.zbkj.admin.pojo.EbUserRelationshipEntity;
import com.zbkj.admin.result.CommonResult;
import com.zbkj.admin.service.EbUserRelationshipService;
import com.zbkj.admin.service.OrderService;
import com.zbkj.admin.service.PayCallbackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Map;
import java.util.Objects;

/**
 * 支付回调
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/publicly/payment/callback")
@Tag(name = "支付回调控制器")
public class PayCallbackController {

    @Autowired
    private PayCallbackService callbackService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DisruptorConfig disruptorConfig;
    @Autowired
    private RDQEventPublisher rdqPublisher;
    @Autowired
    private EbUserRelationshipService userRelationshipService;

    @Operation(summary = "微信支付回调")
    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
    public void weChat(@RequestBody String request) {
        System.out.println("微信支付回调 request ===> " + request);
        String response = callbackService.wechatPayCallback(request);
        System.out.println("微信支付回调 response ===> " + response);
        WebUtil.renderJson(WebUtil.getResponse(), JSON.toJSONString(CommonResult.success(response)));
    }

    @Operation(summary = "支付宝支付回调 ")
    @RequestMapping(value = "/alipay", method = RequestMethod.POST)
    public void aliPay(HttpServletRequest request, HttpServletResponse response) {
        //支付宝支付回调
        Map<String, String> paramMap = JakartaServletUtil.getParamMap(request);
//        Map<String, String> paramMap = JSON.parseObject(JakartaServletUtil.getBody(request),Map.class);
//        System.out.println("汇付支付回调 request ===> " + JSONUtil.formatJsonStr(JSON.toJSONString(paramMap)));
        String escape = JSONUtil.escape(JSON.toJSONString(paramMap));
        JSONObject data = JSON.parseObject(escape, JSONObject.class);
        JSONObject respData = data.getBean("resp_data", JSONObject.class);
        log.info("格式化回调 request ===> " + JSONUtil.formatJsonStr(JSON.toJSONString(respData)));
        log.info("支付状态 request ===> " + respData.getStr("acct_id"));
        WebUtil.renderJson(response, JSON.toJSONString(callbackService.aliPayCallback(respData)));
    }

    @Operation(summary = "第三方回调")
    @RequestMapping(value = "/callback")
    public void callback() {
        HttpServletRequest request = WebUtil.getRequest();
        if (request == null) {
            log.error("request is null");
            return;
        }
        Map<String, String> paramMap = JakartaServletUtil.getParamMap(request);
        String string = paramMap.get("bizData");
        if (StrUtil.isNotBlank(string)) {
            JSONObject entries = JSON.parseObject(string, JSONObject.class);
            if (entries.getStr("resultStatus").equalsIgnoreCase("success")) {
                Order order = orderService.getByOrderNo(entries.getStr("outOrderNo"));
                RingBuffer<OrderEvent> ringBuffer = disruptorConfig.getDisruptor().getRingBuffer();
                OrderEventProducer eventProducer = new OrderEventProducer(ringBuffer);
                if (Objects.nonNull(order)) {
                    String finishedTime = entries.getStr("finishedTime");
                    order.setStatus(1).setPaid(true).setOutTradeNo(entries.getStr("outOrderNo")).setPayTime(DateUtil.parse(finishedTime, "yyyyMMddHHmmss"));
                    orderService.updateById(order);
                    EbUserRelationshipEntity relationshipEntity = userRelationshipService.getOne(userRelationshipService.from().where(EbUserRelationshipEntity::getUid).eq(order.getUid())
                            .eq(EbUserRelationshipEntity::getIsEstablish, 0));

                    if (ObjectUtil.isNotNull(relationshipEntity)) {
                        relationshipEntity.setIsEstablish(1);
                        userRelationshipService.updateById(relationshipEntity);
                    }
//                    RingBuffer<OrderEvent> ringBuffer = disruptorConfig.getDisruptor().getRingBuffer();
//                    OrderEventProducer eventProducer = new OrderEventProducer(ringBuffer);
                    eventProducer.onData(order.getOrderNo(), "pay");
                }
            } else {
                log.error("第三方支付回调订单未支付！！！！！");
            }
        }
        System.out.println("第三方回调 request ===> " + JSONUtil.formatJsonStr(JSON.toJSONString(request.getParameterMap())));
    }

    @Operation(summary = "第三方回调")
    @RequestMapping(value = "/notice")
    public void notice() {
        HttpServletRequest request = WebUtil.getRequest();
        System.out.println("第三方回调 request ===> " + JSONUtil.formatJsonStr(JSON.toJSONString(request.getParameterMap())));
    }

    /**
     * 微信退款回调
     */
    @Operation(summary = "微信退款回调")
    @RequestMapping(value = "/wechat/refund", method = RequestMethod.POST)
    public void weChatRefund(@RequestBody String request) {
        System.out.println("微信退款回调 request ===> " + request);
        String response = callbackService.weChatRefund(request);
        System.out.println("微信退款回调 response ===> " + response);
        WebUtil.renderJson(WebUtil.getResponse(), JSON.toJSONString(CommonResult.success(response)));
    }
}



